import React from "react";
import {ImagePicker,Toast} from "antd-mobile"
import {toAjax} from "../common/toAjax";
export default class UploaderImagePicker extends React.Component{

    state={
        images:this.props.images
    }

    uploadImg = (files, type, index)=>{
        console.log(files, type, index)
        if (files.length === 0){
            this.setState({images: files},()=>{
                this.props.callBackImages([])
            });
            return false;
        }
        this.fileReader(files[0].file);
    }


    //读取文件
    fileReader(file){
        let that = this,fileName = "";
        if(!file){
            return false;
        }
        try {
            fileName = file.name;
        }catch (e) {
            fileName = "text.jpg";
        }
        try {
            if (file.size > 10485760) {
                Toast.fail("上传图片请小于10M",2);
                return;
            }
        }catch (e) {

        }
        Toast.loading("正在上传...",0);
        let reader = new FileReader();
            reader.readAsDataURL(file);
        reader.onload = function(e) {
            if(!this.result){
                Toast.fail("获取原图url为空",2);
                return;
            }
            let img = new Image();
            img.src = this.result;
            if(this.result.length <= 204800){ //图片大小 <= 100kb 直接上传
                //直接上传
                that.upload(this.result.split(",")[1],fileName);
            }else{
                // 图片加载完毕之后进行压缩，然后上传
                if(img.complete){
                    let ndata = that.compress(img);
                    if(!ndata){
                        ndata = this.result.split(",")[1];
                    }
                    that.upload(ndata,fileName);
                }else{
                    img.onload = function () {
                        let ndata = that.compress(img);
                        if(!ndata){
                            ndata = this.result.split(",")[1];
                        }
                        that.upload(ndata,fileName);
                    }
                }
            }
        }
        reader.onerror = function (err) {
            Toast.hide();
            Toast.fail("获取原图url为空",2);
        }
    }

    //压缩图片
   compress(img) {
        let initSize = img.src.length;
        let width = img.width;
        let height = img.height;
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext('2d');
        let tCanvas = document.createElement("canvas");
        let tctx = tCanvas.getContext("2d");
        //如果图片大于1百万像素，计算压缩比并将大小压至100万以下
        let ratio;
        if ((ratio = width * height / 1000000)>1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        }else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        //        铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        let count;
        if ((count = width * height / 1000000) > 1) {
            count = ~~(Math.sqrt(count)+1); //计算要分成多少块瓦片
            //            计算每块瓦片的宽和高
            let nw = ~~(width / count);
            let nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;

            for (let i = 0; i < count; i++) {
                for (let j = 0; j < count; j++) {
                    tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(img, 0, 0, width, height);
        }

        //进行最小压缩
        let ndata = canvas.toDataURL('image/jpeg', 0.5).split(",")[1];

        console.log('压缩前：' + initSize);
        console.log('压缩后：' + ndata.length);
        console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");

        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        return ndata;
    }

    upload(image,fileName){
        toAjax.ajaxPost("https://up.shike8888.com/upload/image",{image:image,fileName:fileName,imgType:1000}).then(res=>{
            if(res.code == 1){
                Toast.hide();
                let images = [{url:res.data.cdn}];
                this.setState({images},()=>{
                    this.props.callBackImages(images)
                })
            }else{
                Toast.hide();
                Toast.fail(res.msg,2)
            }
        })
    }

    render(){
        return(
            <ImagePicker
                files={this.state.images}
                onChange={this.uploadImg}
                onImageClick={(index, fs) => console.log(index, fs)}
                accept="image/jpeg,image/jpg,image/png"
                selectable={this.state.images.length < (this.props.selectable ? this.props.selectable : 1)}
            />
        )
    }
}